package com.hello.redis.util;

import com.hello.redis.exception.ShareLockException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisShareLockUtil {

    @Autowired
    private RedisUtil redisUtil;

    private Long TIME_OUT = 100L;

    /**
     * 获取锁
     * @param lockKey 锁的键
     * @param requestId 请求 ID，用于唯一标识锁的持有者
     * @param time 锁的过期时间，单位：秒
     * @return 是否成功获取锁
     */
    public boolean Lock(String lockKey ,String requestId ,Long time){
        // 1、参数的校验
        if (StringUtils.isBlank(lockKey) || StringUtils.isBlank(requestId) || time <= 0) {
            throw new ShareLockException("分布式锁-加锁参数异常");
        }
        long currentTime = System.currentTimeMillis();
        long outTime = currentTime + TIME_OUT;
        Boolean result = false;
        // 2、加锁可以自旋
        while (currentTime < outTime) {
            // 3、借助redis的setnx来进行锁的设置
            result = redisUtil.setNx(lockKey, requestId, time, TimeUnit.MILLISECONDS);
            if (result) {
                return result;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            currentTime = System.currentTimeMillis();
        }

        return result;
    }

    /**
     * 释放锁
     * @param key 锁的键
     * @param requestId 请求 ID，用于唯一标识锁的持有者
     * @return 是否成功释放锁
     */
    public boolean unLock(String key, String requestId) {
        if (StringUtils.isBlank(key) || StringUtils.isBlank(requestId)) {
            throw new ShareLockException("分布式锁-解锁参数异常");
        }
        try {
            String value = redisUtil.get(key);
            if (requestId.equals(value)) {
                redisUtil.del(key);
                return true;
            }
        } catch (Exception e) {
            //补日志
        }
        return false;
    }

    /**
     * 尝试加锁方法
     */
    public boolean tryLock(String lockKey, String requestId, Long time) {
        if (StringUtils.isBlank(lockKey) || StringUtils.isBlank(requestId) || time <= 0) {
            throw new ShareLockException("分布式锁-尝试加锁参数异常");
        }
        return redisUtil.setNx(lockKey, requestId, time, TimeUnit.MILLISECONDS);
    }
}
